package org.example.common.dispacher;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.netty.channel.*;
import org.example.common.codec.Invocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消息分发器
 * @time 2025/6/16 17:18
 */
@Component
@ChannelHandler.Sharable
public class MessageDispatcher extends SimpleChannelInboundHandler<Invocation> {
    @Autowired
    private MessageHandlerContainer messageHandlerContainer;
    private final ExecutorService executor = Executors.newFixedThreadPool(200);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Invocation invocation) throws Exception {
        // 获得type 对应的 MessageHandler 处理器
        MessageHandler messageHandler = messageHandlerContainer.getMessageHandler(invocation.getType());
        // 获得 MessageHandler 处理器对应的 Message 类
        Class<? extends Message> messageClass = messageHandlerContainer.getMessageClass(messageHandler);
        // 解析消息
        Message message = JSONObject.parseObject(invocation.getMessage(), messageClass);
        // 执行逻辑
        executor.submit(new Runnable() {
            @Override
            public void run() {
                messageHandler.execute(ctx.channel(), message);
            }
        });

    }
}
